package com.wms.handler;

import com.wms.entity.WmsReturnGoods;
import com.wms.entity.WmsReturnGoodsMx;
import com.wms.util.GetStorageSizeUtil;
import com.wms.util.GetStorageSizeUtil.StorageDetail;
import com.wms.util.GetStorageSizeUtil.StorageInfo;
import com.wms.util.WmsStorageUtil;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 *  采购退货单审核
 */
public class WmsReturnGoodsPutCheckHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		boolean isOk = false;
		String msg = "保存失败!";
		try {
			OBContext.setAdminMode();
			JSONObject reqData = new JSONObject(data);
			String id = reqData.getString("recordId");
			boolean isPass = reqData.getBoolean("isPass");
			String description = reqData.getString("description");
			// 新建头信息
			WmsReturnGoods material = OBDal.getInstance().get(WmsReturnGoods.class, id);
			List<WmsReturnGoodsMx> hzList = material.getWmsReturnGoodsMxList();
			if(hzList==null||hzList.size()==0){
				throw new Exception("采购退货明细未维护！");
			}

			material.setId(id);
			material.setStatus(isPass ? "PASS" : "NO_PASS");//通过
			material.setDescription(description);
			String warehouseId = material.getWarehouse().getId();
			String vendorId = material.getEmesVendor() == null ? null : material.getEmesVendor().getId();
			
			if (isPass) {
				StorageInfo info = null;
				//检查数量是否达标(此处指定了货位，可能需要加货位判定)
				
				for (WmsReturnGoodsMx wmsReturnGoodsMx : hzList) {
					if (wmsReturnGoodsMx.getBatchNo() != null) {
						info = GetStorageSizeUtil.getStroageSizeDatail(warehouseId,
								wmsReturnGoodsMx.getLocator() == null ? null : wmsReturnGoodsMx.getLocator().getId(),
								wmsReturnGoodsMx.getProduct().getSearchKey(), vendorId,
								wmsReturnGoodsMx.getQty().doubleValue(),
								wmsReturnGoodsMx.getBatchNo().getBatchNo(), "");
						
						if(info.getSize() <= 0 || info.getSize() < wmsReturnGoodsMx.getQty().doubleValue()){
							throw new Exception("库存数量不足，无法转换，当前物料可用库存为" + info.getSize() + "！");
						}
						  //操作出入库记录
						for (StorageDetail d : info.getList()) {
							WmsStorageUtil.addTakeupStorage(d.getStorage(), new BigDecimal(wmsReturnGoodsMx.getQty().toString()),
									material.getWarehouse(), wmsReturnGoodsMx.getLocator(),  wmsReturnGoodsMx.getId(), 
									wmsReturnGoodsMx.getBatchNo().getBatchNo(), "采购退货", 
									wmsReturnGoodsMx.getProduct().getUOM(), null, null);
						}
					}else{
						break ;
					}
					
				}
			}
			
			OBDal.getInstance().save(material);
			OBDal.getInstance().commitAndClose();
			isOk = true;
			msg = "保存成功!";
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			isOk = false;
			msg = e.getMessage();
			logger.error("采购退货单审核失败：", e);
		} finally {
			OBContext.restorePreviousMode();
			try {
				jsonRep.put("result", isOk);
				jsonRep.put("msg", msg);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return jsonRep;
	}
}